package zero.tech.wsnet.net;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import zero.tech.core.util.EngineLogUtil;
import zero.tech.wsnet.common.ReqProcessManager;
import zero.tech.wsnet.common.ResNodeProcessManager;
import zero.tech.wsnet.net.websocket.WebSocketConfig;
import zero.tech.wsnet.net.websocket.WebSocketServer;
import zero.tech.wsnet.work.HeartBeatWork;

@Configuration
@ConfigurationProperties(prefix = "ws.server")
public class TcpServer {
	private static Logger logger = LoggerFactory.getLogger(TcpServer.class);
	private boolean enable;
	
	@Import(value = { WebSocketConfig.class, WebSocketServer.class })
	protected class InitWs {
	}
	
	@ConditionalOnProperty(name = "enable",prefix = "ws.server",havingValue = "true",matchIfMissing = false)
	@Bean(value = "initws")
	public InitWs init() throws NumberFormatException, IOException {
		initServer();
		new HeartBeatWork().start();
		int cpuNum = Runtime.getRuntime().availableProcessors();
		long totalMemary = Runtime.getRuntime().totalMemory();
		long freeMemary = Runtime.getRuntime().freeMemory();
		long maxMemaryUse = Runtime.getRuntime().maxMemory();
		logger.info("========================================>当前服务器CUP个数:{}", cpuNum);
		logger.info("========================================>当前服务器总内存:{}MB", totalMemary / 1024);
		logger.info("========================================>当前服务器空闲内存:{}MB", freeMemary / 1024);
		logger.info("========================================>当前服务器总最大容量内存:{}MB", maxMemaryUse / 1024);
		logger.info("========================================>连接地址:{}","ws://{ip}:{port}/ws/{context}/engine/{userId}");
		return new InitWs();
	}

	private void initServer() {
		try {
			ReqProcessManager.getManager().start();
			ResNodeProcessManager.getManager().start();
		} catch (Exception e) {
			EngineLogUtil.traceFull(e);
			System.exit(0);
		}
	}

	public boolean isEnable() {
		return enable;
	}

	public void setEnable(boolean enable) {
		this.enable = enable;
	}
}
